<template>
  <uni-data-picker
    ref="picker"
    placeholder="请选择"
    popup-title="请选择"
    :localdata="dataTree"
    v-model="data"
    :clear-icon="false"
    @change="onchange"
    @nodeclick="onnodeclick"
    @popupopened="onpopupopened"
    @popupclosed="onpopupclosed"
    :map="{ text: 'name', value: 'id' }"
    :step-searh="true"
  >
  </uni-data-picker>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch,
  onMounted,
  getCurrentInstance,
} from 'vue'

const emit = defineEmits(['onchange'])
const props = defineProps({
  propData: {
    type: String,
    default: '',
  },

  data: {
    type: Array,
    default: () => [],
  },

  httpRequest: {
    type: Function,
    default: async () => {},
  },
})
const { httpRequest, data } = toRefs(props)

const picker = ref()

const onnodeclick = (e: any) => {
  console.log(e)
}
const onpopupopened = (e: any) => {
  console.log('popupopened')
  initData()
}
const onpopupclosed = (e: any) => {
  console.log('popupclosed')
}
const onchange = (e: any) => {
  emit('onchange', e.detail.value)
}

onMounted(() => {
  initData()
})

const initData = async () => {
  if (httpRequest.value != undefined && dataTree.value.length === 0) {
    try {
      const res = await httpRequest.value()
      if (!res.data.length) {
        uni.showToast({
          title: '加载数据异常,请刷新重试!',
          icon: 'error',
        })
      } else {
        dataTree.value = res.data as any
      }
    } catch (error) {
      uni.showToast({
        title: '加载数据异常,请刷新重试!',
        icon: 'error',
      })
    }
  }
}

const { dataTree, classes } = toRefs(
  reactive({
    classes: [13, 149, 1587],
    //定义数组和对象
    dataTree: [],
  })
)
</script>

<style>
::v-deep .selected-item {
  font-size: 0.7rem;
}
</style>
<style lang="scss" scoped></style>
